<template>
  <div class="employee-container">
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="form-inline">
        <el-form-item label="员工姓名">
          <el-input v-model="filterForm.name" placeholder="请输入员工姓名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="operation-container">
      <el-button
        v-if="username === '管理员'"
        type="primary" @click="handleAdd">新增员工</el-button>
    </div>
    
    <el-table
      :data="employeeList"
      border
      style="width: 100%"
      v-loading="loading">
      <el-table-column
        type="index"
        label="序号"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="员工姓名"
        width="120">
      </el-table-column>
      <el-table-column
        prop="username"
        label="账号"
        width="150">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="手机号码"
        width="150">
      </el-table-column>
      <el-table-column
        prop="sex"
        label="性别"
        width="80">
        <template slot-scope="scope">
          {{ scope.row.sex === '1' ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100">
        <template slot-scope="scope">
          <el-switch
            v-if="username === '管理员'"
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)">
          </el-switch>
          <el-tag
            v-else
            :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180">
      </el-table-column>
      <el-table-column
        label="操作"
        width="280">
        <template slot-scope="scope">
          <el-button
            v-if="username === '管理员'"
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            v-if="username === '管理员'"
            size="mini"
            type="primary"
            @click="handleResetPassword(scope.row)">重置密码</el-button>
          <el-button
            v-if="username === '管理员'"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    
    <!-- 新增/编辑员工对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="employeeForm" :rules="rules" ref="employeeForm" label-width="100px">
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入员工姓名"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="employeeForm.username" placeholder="请输入账号" :disabled="dialogType === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="employeeForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="employeeForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="employeeForm.idNumber" placeholder="请输入身份证号"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="500px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" placeholder="请输入旧密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" placeholder="请再次输入新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPasswordForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEmployeeList,
  addEmployee,
  updateEmployee,
  getEmployeeById,
  updateEmployeeStatus,
  updatePassword,
  deleteEmployee
} from '@/api/employee'

export default {
  name: 'EmployeeManagement',
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    
    // 身份证号验证规则
    const validateIdNumber = (rule, value, callback) => {
      if (value && !/^\d{17}(\d|X|x)$/.test(value)) {
        callback(new Error('请输入正确的身份证号码'))
      } else {
        callback()
      }
    }
    
    // 确认密码验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    return {
      username: '',
      // 筛选表单
      filterForm: {
        name: '',
      },
      // 员工列表
      employeeList: [],
      // 加载状态
      loading: false,
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增员工',
      dialogType: 'add', // add 或 edit
      // 表单
      employeeForm: {
        id: null,
        name: '',
        username: '',
        phone: '',
        sex: 1,
        idNumber: '' // 身份证号
      },
      // 修改密码对话框
      passwordDialogVisible: false,
      // 当前操作的员工ID
      currentEmployeeId: null,
      // 密码表单
      passwordForm: {
        empId: null,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validateIdNumber, trigger: 'blur' }
        ]
      },
      // 密码表单验证规则
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 组件创建时加载员工列表
    this.handleSearch()

    // 从本地存储获取用户信息
    const userInfo = localStorage.getItem('userInfo')
    if (userInfo) {
      const user = JSON.parse(userInfo)
      this.username = user.name || '管理员'
    }

  },
  methods: {
    // 查询
    handleSearch() {
      this.loading = true
      // 构建查询参数
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize
      }
      
      // 添加可选查询条件
      if (this.filterForm.name) {
        params.name = this.filterForm.name
      }
      
      // 调用API获取员工列表
      getEmployeeList(params)
        .then(res => {
          if (res.code === 1) {
            this.employeeList = res.data.records
            this.total = res.data.total
            this.$message.success('查询成功')
          } else {
            this.$message.error(res.msg || '查询失败')
          }
        })
        .catch(err => {
          console.error('获取员工列表失败', err)
          this.$message.error('获取员工列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 重置表单
    resetForm() {
      this.filterForm = {
        name: '',
        phone: '',
        status: ''
      }
    },
    // 新增员工
    handleAdd() {
      this.dialogTitle = '新增员工'
      this.dialogType = 'add'
      this.employeeForm = {
        id: null,
        name: '',
        username: '',
        phone: '',
        sex: 1,
        idNumber: ''
      }
      this.dialogVisible = true
      // 在下一个事件循环中重置表单验证
      this.$nextTick(() => {
        if (this.$refs.employeeForm) {
          this.$refs.employeeForm.resetFields()
        }
      })
    },
    // 编辑员工
    handleEdit(row) {
      this.dialogTitle = '编辑员工'
      this.dialogType = 'edit'
      this.loading = true
      
      // 根据ID获取员工详细信息
      getEmployeeById(row.id)
        .then(res => {
          if (res.code === 1) {
            // 设置表单数据
            this.employeeForm = {
              id: res.data.id,
              name: res.data.name,
              username: res.data.username,
              phone: res.data.phone,
              sex: Number(res.data.sex),
              idNumber: res.data.idNumber
            }
            this.dialogVisible = true
          } else {
            this.$message.error(res.msg || '获取员工信息失败')
          }
        })
        .catch(err => {
          console.error('获取员工信息失败', err)
          this.$message.error('获取员工信息失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 删除员工
    handleDelete(row) {
      this.$confirm('确认删除该员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除员工API
        this.loading = true
        deleteEmployee(row.id)
          .then(res => {
            if (res.code === 1) {
              // 删除成功，更新列表
              this.$message.success('删除成功')
              // 刷新列表数据
              this.handleSearch()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          })
          .catch(err => {
            console.error('删除员工失败', err)
            this.$message.error('删除员工失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 打开修改密码对话框
    handleResetPassword(row) {
      this.currentEmployeeId = row.id
      this.passwordForm = {
        empId: row.id,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      this.passwordDialogVisible = true
      // 在下一个事件循环中重置表单验证
      this.$nextTick(() => {
        if (this.$refs.passwordForm) {
          this.$refs.passwordForm.resetFields()
        }
      })
    },
    
    // 提交修改密码表单
    submitPasswordForm() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 构建请求参数
          const params = {
            empId: this.passwordForm.empId,
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword
          }
          
          // 调用修改密码API
          updatePassword(params)
            .then(res => {
              if (res.code === 1) {
                this.$message.success('密码修改成功')
                this.passwordDialogVisible = false
              } else {
                this.$message.error(res.msg || '密码修改失败')
              }
            })
            .catch(err => {
              console.error('密码修改失败', err)
              this.$message.error('密码修改失败')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    // 状态变更
    handleStatusChange(row) {
      const status = row.status
      const statusText = status === 1 ? '启用' : '禁用'
      
      this.loading = true
      updateEmployeeStatus(row.id, status)
        .then(res => {
          if (res.code === 1) {
            this.$message.success(`员工「${row.name}」已${statusText}`)
          } else {
            // 恢复原状态
            row.status = status === 1 ? 0 : 1
            this.$message.error(res.msg || `${statusText}失败`)
          }
        })
        .catch(err => {
          // 恢复原状态
          row.status = status === 1 ? 0 : 1
          console.error(`${statusText}员工失败`, err)
          this.$message.error(`${statusText}员工失败`)
        })
        .finally(() => {
          this.loading = false
          // 刷新列表
          this.handleSearch()
        })
    },
    // 提交表单
    submitForm() {
      this.$refs.employeeForm.validate(valid => {
        if (valid) {
          this.loading = true
          
          if (this.dialogType === 'edit') {
            // 编辑员工
            updateEmployee(this.employeeForm)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success('编辑成功')
                  this.dialogVisible = false
                  // 刷新列表
                  this.handleSearch()
                } else {
                  this.$message.error(res.msg || '编辑失败')
                }
              })
              .catch(err => {
                console.error('编辑员工失败', err)
                this.$message.error('编辑员工失败')
              })
              .finally(() => {
                this.loading = false
              })
          } else {
            // 新增员工
            addEmployee(this.employeeForm)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success('新增成功')
                  this.dialogVisible = false
                  // 刷新列表
                  this.handleSearch()
                } else {
                  this.$message.error(res.msg || '新增失败')
                }
              })
              .catch(err => {
                console.error('新增员工失败', err)
                this.$message.error('新增员工失败')
              })
              .finally(() => {
                this.loading = false
              })
          }
        }
      })
    },
    // 页码改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.handleSearch()
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val
      this.handleSearch()
    }
  }
}
</script>

<style scoped>
.employee-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>